﻿module Sustainalytics.Company {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;
    import Routing = Sustainalytics.Routing;

    // Company List controller
    export class CompanyListController {
        // order by
        public orderByCol: string;
        public orderByAsc: boolean;

        // list of Companys
        public companyList: CorporateDataDto[];
        
        // total number of Companys
        public companyCount: number;
        public hasCompanyPermision: boolean;

        //filter options
        public hasResearchOptions: any[] = [
            { value: true, text: 'Yes' },
            { value: false, text: 'No' }
        ];

        
        //filter value object
        public compFilters: CompanyListFilters = new CompanyListFilters();


        private scopeDestroyed: boolean;

        public hasGccsClaim: boolean;
        public hasPiClaim: boolean;
        public hasGovernanceClaim: boolean;
        public hasEsgClaim: boolean;
        public hasControvercyClaim: boolean;
        public hasRiskClaim: boolean;

        public hasLegendBox: boolean;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private CompanyService: CompanyService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private $modal: Common.IModal,
            private RoutingService: Routing.RoutingService){

            var ctx = this;


            ctx.compFilters.hasEsgResearch = null;
            ctx.compFilters.hasGovernanceResearch = null;
            ctx.compFilters.hasControversyResearch = null;
            ctx.compFilters.hasGccsResearch = null;
            ctx.compFilters.hasPIResearch = null;
            ctx.compFilters.hasRiskResearch = null;

            $scope['companyList'] = ctx;

            ctx.scopeDestroyed = false;
            ctx.orderByCol = "CompanyNameLowercase";
            ctx.orderByAsc = true;

            ctx.handlePagerChanged();
            ctx.handleScopeDestroyed();

            //GCCS
            var gcRouteSecurity = new Routing.RouteSecurity().addService('GCRouteSecurityService');
            var gcPromise = ctx.RoutingService.validateRouteSecurity(gcRouteSecurity);
            gcPromise.then(function (val) {
                ctx.hasGccsClaim = val;
            });

            //PIResearch
            var piRouteSecurity = new Routing.RouteSecurity().addService('PICompanyRouteSecurityService');
            var piPromise = ctx.RoutingService.validateRouteSecurity(piRouteSecurity);
            piPromise.then(function (val) {
                ctx.hasPiClaim = val;
            });

            //governance
            var govRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'GET', resource: 'api/v1/governance', parameters: [] });
            var govPromise = ctx.RoutingService.validateRouteSecurity(govRouteSecurity);
            govPromise.then(function (val) {
                ctx.hasGovernanceClaim = val;
            });

            //esg research
            var esgRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'GET', resource: 'api/v1/esgratings/{companyId}', parameters: [] });
            var esgPromise = ctx.RoutingService.validateRouteSecurity(esgRouteSecurity);
            esgPromise.then(function (val) {
                ctx.hasEsgClaim = val;
            });

            //esg research
            var riskRouteSecurity = new Routing.RouteSecurity().addResource({verb: 'GET', resource: 'api/v1/riskratings/{companyId}', parameters: [] });
            var riskPromise = ctx.RoutingService.validateRouteSecurity(riskRouteSecurity);
            riskPromise.then(function (val) {
                ctx.hasRiskClaim = val;
            });

            //controvercy
            var controvercyRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'GET', resource: 'api/v1/company/{companyId}/esgControversyIndicator', parameters: [] });
            var controvercyPromise = ctx.RoutingService.validateRouteSecurity(controvercyRouteSecurity);
            controvercyPromise.then(function (val) {
                ctx.hasControvercyClaim = val;
            });

            ctx.hasLegendBox = true;
        }

        // when scope is destroyed keep a flag to prevent some operations
        // eg: bootstrap UI tab delete each tab and select the next that causing 
        // in current case to trigger multiple requests while tabs are being disposed 
        // which is unnecessary
        private handleScopeDestroyed() {
            var ctx = this;

            // when scope is destroyed
            ctx.$scope.$on('$destroy', function () {
                ctx.scopeDestroyed = true;
            });
        }

        // search for Companys when pager changes
        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function (ev, pager: Pager.PagerController) {
                ctx.searchCompany();
            });
        }

        // order list of Companys
        public setOrderByCol(col: string) {
            var ctx = this;
           
            if (ctx.orderByCol === col) {
                ctx.orderByAsc = !ctx.orderByAsc;
            }
            else {
                if (col === "HasEsgResearch" ||
                    col === "HasGovernanceResearch" ||
                    col === "HasControversyResearch" ||
                    col === "HasGccsResearch" ||
                    col === "PIResearchState" ||
                    col === "HasRiskRatingResearch") {
                    ctx.orderByCol = col;
                    ctx.orderByAsc = false;
                } else {
                    ctx.orderByCol = col;
                    ctx.orderByAsc = true;
                }
            }
            ctx.searchCompany();
        }

        public hasResearchAvailable(researchType, company): boolean {
            var result = false;

            if (researchType === "esg") {
                if (company.comprehensiveEsgResearchState === 2 || company.coreEsgResearchState === 2) {
                    result = true;
                }
            }
            if (researchType === "gov") {
                if (company.corporateGovernanceResearchState === 2) {
                    result = true;
                }
            }
            if (researchType === "contr") {
                if (company.controversyResearchState === 2) {
                    result = true;
                }
            }
            if (researchType === "gccs") {
                if (company.gccsResearchState === 2) {
                    result = true;
                }
            }
            if (researchType === "pi") {
                if (company.productInvolvementResearchState === 2) {
                    result = true;
                }
            }
            if (researchType === "risk") {
                if (company.riskRatingResearchState === 2) {
                    result = true;
                }
            }
            return result;
        }

        public hasResearchInProgress(researchType, company): boolean {
            var ctx = this;
            var result = false;

            if (!ctx.hasResearchAvailable(researchType, company)) {
                if (researchType === "esg") {
                    if (company.comprehensiveEsgResearchState === 1 || company.coreEsgResearchState === 1) {
                        result = true;
                    }
                }
                if (researchType === "gov") {
                    if (company.corporateGovernanceResearchState === 1) {
                        result = true;
                    }
                }
                if (researchType === "contr") {
                    if (company.controversyResearchState === 1) {
                        result = true;
                    }
                }
                if (researchType === "gccs") {
                    if (company.gccsResearchState === 1) {
                        result = true;
                    }
                }
                if (researchType === "pi") {
                    if (company.productInvolvementResearchState === 1) {
                        result = true;
                    }
                }
                if (researchType === "risk") {
                    if (company.riskRatingResearchState === 1) {
                        result = true;
                    }
                }
            }

            return result;
        }

        public hasResearchNotAvailable(researchType, company): boolean {
            var ctx = this;
            var result = false;

            if (!ctx.hasResearchInProgress(researchType, company)) {
                if (researchType === "esg") {
                    if ((company.comprehensiveEsgResearchState === 0 || company.comprehensiveEsgResearchState === 3) &&
                        (company.coreEsgResearchState === 0 || company.coreEsgResearchState === 3)) {
                        result = true;
                    }
                }
                if (researchType === "gov") {
                    if (company.corporateGovernanceResearchState === 0 || company.corporateGovernanceResearchState === 3) {
                        result = true;
                    }
                }
                if (researchType === "contr") {
                    if (company.controversyResearchState === 0 || company.controversyResearchState === 3) {
                        result = true;
                    }
                }
                if (researchType === "gccs") {
                    if (company.gccsResearchState === 0 || company.gccsResearchState === 3) {
                        result = true;
                    }
                }
                if (researchType === "pi") {
                    if (company.productInvolvementResearchState === 0 || company.productInvolvementResearchState === 3) {
                        result = true;
                    }
                }
                if (researchType === "risk") {
                    if (company.riskRatingResearchState === 0 || company.riskRatingResearchState === 3) {
                        result = true;
                    }
                }
            }

            return result;
        }

        public GetHasResearchTypeEnabled(resType, val): boolean {
            var ctx = this;
            var result = false;

            for (var prop in ctx.compFilters) {
                if (prop.toLowerCase().indexOf(resType) > -1) {
                    result = ctx.compFilters[prop] === val;
                    break;
                }
            }
            return result;
        }

        public ChangeHasResearchType(resType, val) {
            var ctx = this;

            for (var prop in ctx.compFilters)
            {
                if (prop.toLowerCase().indexOf(resType) > -1) {
                    ctx.compFilters[prop] = val;
                    break;
                }
            }

            console.log(ctx.compFilters);

            ctx.searchButtonClick();
        }

        public searchButtonClick() {
            var ctx = this;

            // go to page 1
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
                return;

            pager.goTo(1);
        }

        // search list of Companys
        public searchCompany(): ng.IPromise<{}> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;


            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager) {
                var def = ctx.$q.defer();
                def.reject();
                return def.promise;
            }

            var skip = pager.skipCount();
            var take = pager.takeCount();

            // get Company items
            var promiseGet: ng.IPromise<CorporateDataDto[]> = ctx.CompanyService.getCompanies(ctx.compFilters, skip, take, ctx.orderByCol, ctx.orderByAsc);

            var companyListTemp: CorporateDataDto[];

            //on success list Companys
            promiseGet.then(function (lst) {
                companyListTemp = lst;
            });

            //get Companys count
            var promiseCount: ng.IPromise<number> = ctx.CompanyService.getCompaniesCount(ctx.compFilters);

            var CompanyCountTemp: number;

            //on success 
            promiseCount.then(function (count) {
                CompanyCountTemp = count;
            });

            // after get and count are resolved set controller properties
            var promiseAll = ctx.$q.all([promiseGet, promiseCount]);

            promiseAll
                .then(function () {
                    ctx.companyList = companyListTemp;
                    ctx.companyCount = CompanyCountTemp['companyCount'];
                    pager.setTotalItemsCount(CompanyCountTemp['companyCount']);
                })
            ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

            return promiseAll;
        }

        public closeLegendBox() {
            var ctx = this;
            ctx.hasLegendBox = false;
        }
    }


    // register controller with News Angular module
    angular.module('Sustainalytics.Company').controller('CompanyListController',
        ['$rootScope', '$scope', '$q', '$location', 'CompanyService', 'notificationFactory', 'staticObjects', '$modal', 'RoutingService', CompanyListController]);
}  